package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"log/slog"
	"os"
	"strings"

	"gitee.com/xuender/bindgen/internal"
	"github.com/xuender/kit/los"
)

// nolint:gochecknoglobals
var (
	version = "dev"
	date    = "unknown"
)

func main() {
	flag.Usage = usage
	flag.Parse()

	path := los.Must(os.Getwd())
	ctx := context.WithValue(context.Background(), internal.KeyVersion, version)
	ctx = context.WithValue(ctx, internal.KeyDate, date)

	outs, errs := internal.Generate(ctx, path, os.Environ(), flag.Args(), nil)
	if len(errs) > 0 {
		logErrors(errs)
		slog.Info("generate failed")

		return
	}

	if len(outs) == 0 {
		return
	}

	success := true

	for _, out := range outs {
		if len(out.Errs) > 0 {
			logErrors(out.Errs)
			log.Printf("%s: generate failed\n", out.PkgPath)

			success = false
		}

		if len(out.Content) == 0 {
			continue
		}

		if err := out.Commit(); err == nil {
			log.Printf("%s: wrote %s\n", out.PkgPath, out.OutputPath)
		} else {
			log.Printf("%s: failed to write %s: %v\n", out.PkgPath, out.OutputPath, err)

			success = false
		}
	}

	if !success {
		slog.Info("at least one generate failure")

		return
	}
}

func logErrors(errs []error) {
	for _, err := range errs {
		slog.Info(strings.ReplaceAll(err.Error(), "\n", "\n\t"))
	}
}

func usage() {
	fmt.Fprintf(os.Stderr, "bindgen\n\n")
	fmt.Fprintf(os.Stderr, "Given one or more packages, gen creates the bin_gen.go file for each.\n\n")
	fmt.Fprintf(os.Stderr, "Usage: %s [flags] package...\n\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "Vesion:    %s\n", version)
	fmt.Fprintf(os.Stderr, "BuildTime: %s\n", date)
	flag.PrintDefaults()
}
